<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="4">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>角色列表</span>
          </div>
          <el-tree
            :data="roleTree"
            :props="defaultProps"
            @node-click="handleRoleClick"
            :highlight-current="true"
            default-expand-all
          />
        </el-card>
      </el-col>
      <el-col :span="20">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>{{ currentRoleName }} - 字段权限配置</span>
          </div>

          <el-form :inline="true" size="small" style="margin-bottom: 10px;">
            <el-form-item label="选择岗位">
              <el-select v-model="selectedPostId" placeholder="请选择岗位" @change="handlePostChange">
                <el-option
                  v-for="template in templateList"
                  :key="template.id"
                  :label="template.postName"
                  :value="template.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSavePermissions" :disabled="!currentRoleId || !selectedPostId">保存权限</el-button>
            </el-form-item>
          </el-form>

          <el-table
            v-loading="loading"
            :data="fieldList"
            border
            style="width: 100%"
          >
            <el-table-column label="字段名" prop="fieldName" width="150" />
            <el-table-column label="字段显示名称" prop="fieldLabel" width="150" />
            <el-table-column label="字段类型" prop="fieldType" width="120" />
            <el-table-column label="是否有权限" width="180" align="center">
              <template slot-scope="scope">
                <el-switch
                  v-model="scope.row.hasPermission"
                  active-text="有权限"
                  inactive-text="无权限"
                  @change="handlePermissionChange(scope.row)"
                />
              </template>
            </el-table-column>
            <el-table-column label="备注" prop="remark">
              <template slot-scope="scope">
                <el-input v-model="scope.row.remark" size="small" placeholder="请输入备注" />
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { listRole } from "@/api/system/role";
import { listTemplate, getTemplateFields } from "@/api/talent/template";
import { getPermissionsByRoleAndTable, batchSavePermissions } from "@/api/talent/permission";

export default {
  name: "TalentPermission",
  data() {
    return {
      // 遮罩层
      loading: false,
      // 角色树
      roleTree: [],
      // 当前选中角色
      currentRoleId: null,
      currentRoleName: "",
      // 模板列表
      templateList: [],
      // 选中的岗位ID
      selectedPostId: null,
      // 当前模板表名
      currentTableName: "",
      // 字段列表
      fieldList: [],
      // 树属性
      defaultProps: {
        children: 'children',
        label: 'roleName'
      }
    };
  },
  created() {
    this.getRoleList();
    this.getTemplateList();
  },
  methods: {
    /** 查询角色列表 */
    getRoleList() {
      listRole().then(response => {
        this.roleTree = this.handleTree(response.rows, "roleId");
      });
    },
    /** 查询模板列表 */
    getTemplateList() {
      listTemplate({ pageNum: 1, pageSize: 100 }).then(response => {
        this.templateList = response.rows;
      });
    },
    /** 点击角色节点 */
    handleRoleClick(data) {
      this.currentRoleId = data.roleId;
      this.currentRoleName = data.roleName;
      this.selectedPostId = null;
      this.fieldList = [];
    },
    /** 岗位变化 */
    handlePostChange(templateId) {
      const template = this.templateList.find(t => t.id === templateId);
      if (template) {
        this.currentTableName = template.tableName;
        this.loadFieldsAndPermissions(templateId);
      }
    },
    /** 加载字段和权限 */
    loadFieldsAndPermissions(templateId) {
      this.loading = true;

      // 获取字段列表
      getTemplateFields(templateId).then(response => {
        const fields = response.data;

        // 获取该角色对该表的权限
        if (this.currentRoleId && this.currentTableName) {
          getPermissionsByRoleAndTable(this.currentRoleId, this.currentTableName).then(permResponse => {
            const permissions = permResponse.data;

            // 合并字段和权限（简化版：只有"有权限"和"无权限"）
            this.fieldList = fields.map(field => {
              const permission = permissions.find(p => p.fieldName === field.fieldName);
              return {
                ...field,
                hasPermission: permission ? true : false, // 转换为布尔值
                permissionType: permission ? permission.permissionType : '', // 保留原始值
                remark: permission ? permission.remark : '',
                permissionId: permission ? permission.id : null
              };
            });

            this.loading = false;
          });
        } else {
          this.fieldList = fields.map(field => ({
            ...field,
            hasPermission: false,
            permissionType: '',
            remark: '',
            permissionId: null
          }));
          this.loading = false;
        }
      }).catch(() => {
        this.loading = false;
      });
    },
    /** 权限开关变化 */
    handlePermissionChange(row) {
      // 有权限 = "1"（读写），无权限 = ""（空）
      row.permissionType = row.hasPermission ? '1' : '';
    },
    /** 保存权限 */
    handleSavePermissions() {
      if (!this.currentRoleId || !this.selectedPostId) {
        this.$modal.msgError("请选择角色和岗位");
        return;
      }

      // 获取当前角色名称
      const role = this.findRole(this.roleTree, this.currentRoleId);
      const roleName = role ? role.roleName : '';

      // 过滤有权限的字段
      const permissions = this.fieldList
        .filter(field => field.permissionType !== '')
        .map(field => ({
          roleId: this.currentRoleId,
          roleName: roleName,
          templateTable: this.currentTableName,
          fieldName: field.fieldName,
          fieldLabel: field.fieldLabel,
          permissionType: field.permissionType,
          remark: field.remark
        }));

      batchSavePermissions(this.currentRoleId, this.currentTableName, permissions).then(response => {
        this.$modal.msgSuccess("保存成功");
      });
    },
    /** 递归查找角色 */
    findRole(tree, roleId) {
      for (let node of tree) {
        if (node.roleId === roleId) {
          return node;
        }
        if (node.children) {
          const result = this.findRole(node.children, roleId);
          if (result) return result;
        }
      }
      return null;
    }
  }
};
</script>

<style scoped>
.box-card {
  min-height: 600px;
}
</style>

